package com.eascs.web.p2p.member.controller;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.common.util.StringUtil;
import com.eascs.p2p.common.entity.InvestorEntity;
import com.eascs.p2p.common.service.IMessageService;
import com.eascs.p2p.common.service.IMsgSmsService;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.captcha.controller.CaptchaBuilder;
import com.eascs.web.captcha.patchca.service.Captcha;
import com.eascs.web.context.ResponseContext;

@Controller
public class CommonRestController  extends BaseRestController{
	@Reference
	IMsgSmsService msgSmsService;
	@Value("${p2p.h5.register.msg.templateCode}")
	private String templateCode;
	
	private CaptchaBuilder captchaBuilder = new CaptchaBuilder();
	
	@RequestMapping(value = "/common/getCaptcha")
	public void buidCaptchaImage(HttpServletResponse resp) {
		ResponseContext.setContentType(MediaType.IMAGE_PNG_VALUE);
		ResponseContext.setDateHeader("Expries", 0);
		ResponseContext.setHeader("Pragma", "no-cache");
		Captcha captcha = captchaBuilder.buildCaptcha();
		CaptchaBuilder.SESSION_CAPTCHA.setValue(captcha.getChallenge());
		try {
			ImageIO.write(captcha.getImage(), "png", ResponseContext.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/common/checkCaptcha")
	public BaseRestResult<Boolean> checkCaptcha(String captcha){
		String captchaCode=CaptchaBuilder.SESSION_CAPTCHA.getValue();
		if(!captchaCode.equals(captcha)){
			return BaseRestResult.buildRestResult(false);
		}
		return BaseRestResult.buildRestResult(true);
	}
	
	@RequestMapping(value = "/common/sendAuthCode", method = RequestMethod.GET)
	public BaseRestResult<Boolean> sendAuthCode(String mobile) {
		if(StringUtil.isEmpty(mobile)){
			return BaseRestResult.buildRestResult(false);
		}
		ModelResult<Boolean> msgModelResult =msgSmsService.sendAuthCode(templateCode, mobile);
		if(msgModelResult.isSuccess()){
			return BaseRestResult.buildRestResult(msgModelResult.getModel());
		}
		return BaseRestResult.buildRestResult(true);
	}
}
